<template>
  <div style="height: 88vh">
    <el-table
      :data="tableData"
      style="width: 100%; height: 100%; overflow: auto"
      :highlight-current-row="true"
      :default-sort="{
        prop: ['date', 'name', 'located', 'scopeTime', 'state'],
        order: 'descending',
      }"
      header-cell-class-name="th"
      row-class-name="row"
    >
      <el-table-column
        align="center"
        prop="date"
        sortable
        label="日期"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="name"
        sortable
        label="阅览室"
        width="200"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="located"
        sortable
        label="地点"
        width="200"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="scopeTime"
        sortable
        label="时间"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="state"
        sortable
        label="预约状态"
        width="120"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.state == '待签到'" style="color: orange">
            待签到
          </div>
          <div v-else-if="scope.row.state == '已签到'" style="color: green">
            已签到
          </div>
          <div v-else-if="scope.row.state == '已过期'" style="color: purple">
            已过期
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="开放时间" width="auto">
        <template slot-scope="scope">
          <el-tag
            v-for="(day, index) of JSON.parse(scope.row.open_time)"
            :key="index"
            style="margin-left: 6px"
            >{{ day }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="座位" width="100">
        <template slot-scope="scope">
          <span>{{
            scope.row.type +
            "-" +
            scope.row.row +
            "-" +
            scope.row.col +
            "-" +
            scope.row.idx
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="open"
        label="阅览室状态"
        width="200"
      >
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-dropdown size="medium">
            <i class="el-icon-setting" style="margin-right: 5px"></i>
            <el-dropdown-menu
              slot="dropdown"
              v-if="scope.row.state == '待签到'"
            >
              <div @click="changeDate(scope.row, scope.$index)">
                <el-dropdown-item>更改时间</el-dropdown-item>
              </div>

              <div @click="cancel(scope.row.id, scope.$index)">
                <el-dropdown-item>取消预约</el-dropdown-item>
              </div>

              <div @click="signIn(scope.row.id, scope.$index)">
                <el-dropdown-item>签到</el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="更改预约时间"
      :visible.sync="dialogFormVisible"
      v-if="open_time && dialogFormVisible"
    >
      <time-picker
        @updateState="updateState"
        :open_time="JSON.parse(open_time)"
        :timer="timer"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAppointment,
  cancelAppointment,
  changeDate,
  appointmentInDateTime,
  appointmentInDateTimeByOther,
  check,
} from "@network/student";

import TimePicker from "@components/content/TimePicker";
export default {
  components: {
    TimePicker,
  },
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      forbidDay: null,
      open_time: null,
      timer: {
        date: null,
        startTime: null,
        endTime: null,
      },
      resetDate: null,
      appointment_id: null,
      index: null,
    };
  },
  activated() {
    this.getData();
  },
  methods: {
    signIn(appointment_id, index) {
      this.$confirm("确定签到?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await check({ appointment_id }).then((res) => {
            if (res.data.tag) {
              this.$message.success("签到成功!");
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message.info("已取消签到");
        });

      console.log("appointmentid", "位于数组下标", appointment_id, index);
      l;
    },
    updateState(data) {
      let { startTime, endTime } = data,
        date;
      if (typeof data.date == "string") date = data.date;
      else
        date = new Date(new Date(data.date).getTime() + 8 * 60 * 60 * 1000)
          .toISOString()
          .slice(0, 10);
      console.log("updateState", startTime, endTime, date);
      startTime = date + " " + startTime;
      endTime = date + " " + endTime;
      this.resetDate = {
        date,
        startTime,
        endTime,
      };
    },
    shrinkEndTime(time1) {
      if (time1.slice(-2) == "00") {
        let time = parseInt(time1.slice(0, 2)) - 1;
        time1 = (time < 10 ? "0" + time : time) + ":59";
      } else if (time1.slice(-2) == "30") {
        time1 = time1.replace("30", "29");
      }
      return time1;
    },
    enlargeStartTime(time1) {
      time1 = time1.replace("00", "01");
      time1 = time1.replace("30", "31");
      return time1;
    },
    async confirm() {
      if (this.resetDate && this.appointment_id) {
        let start_time = this.resetDate.startTime,
          end_time = this.resetDate.endTime,
          date = this.resetDate.date;
        const { room_id, appointment_id } = this;
        console.log("...this.resetDate", start_time, end_time, date, room_id);
        const shrinkEndTime = this.shrinkEndTime(end_time),
          enlargeStartTime = this.enlargeStartTime(start_time);
        await appointmentInDateTimeByOther({
          start_time: enlargeStartTime,
          end_time: shrinkEndTime,
          room_id,
          date,
          appointment_id,
        }).then(async (res) => {
          if (!res.data.tag) {
            await appointmentInDateTime({
              start_time: enlargeStartTime,
              end_time: shrinkEndTime,
              date,
              appointment_id,
            }).then(async (res) => {
              if (!res.data.tag) {
                await changeDate({
                  ...this.resetDate,
                  appointment_id: this.appointment_id,
                }).then((res) => {
                  this.dialogFormVisible = false;
                  if (res.data.tag) {
                    this.$message.success("更改预约时间成功");
                    this.tableData[this.index].date = this.resetDate.date;
                    this.tableData[this.index].scopeTime =
                      this.timer.startTime + "~" + this.timer.endTime;
                  } else {
                    this.$message.warning("修改预约时间失败,请稍后重试");
                  }
                });
              } else {
                this.$message.error(
                  "该时间段您已有预约,请查看您的预约"
                );
              }
            });
          } else {
            this.$message.error("该阅览室的此时段已被预约");
          }
        });
      } else {
        this.$message.error("未更改时间");
      }
    },

    getData() {
      getAppointment().then((res) => {
        console.log("appointment", res.data.data);
        if (res.data.tag) {
          res.data.data.forEach((v, i) => {
            v.scopeTime =
              v.start_time.slice(-8, -3) + "~" + v.end_time.slice(-8, -3);
            v.date = v.date.slice(0, 10);
            v.open = v.open ? "阅览室可用" : "阅览室已关闭";
          });
          this.tableData = res.data.data;
        }
      });
    },

    changeDate(data, index) {
      this.dialogFormVisible = true;
      console.log("changeDate", data);
      this.room_id = data.room_id;
      this.timer.date = data.date;
      this.timer.startTime = data.scopeTime.slice(0, 5);
      this.timer.endTime = data.scopeTime.slice(6);
      this.open_time = data.open_time;
      this.appointment_id = data.id;
      this.index = index;
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    cancel(appointment_id, index) {
      console.log("index", index);
      this.$confirm("确定取消该预约?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log("appointment_id", appointment_id);
          await cancelAppointment({ appointment_id }).then((res) => {
            if (res.data.tag) {
              this.$message.success("取消预约成功!");
              let data = this.tableData;
              this.$set(this, "tableData", [
                ...data.slice(0, index),
                ...data.slice(index + 1),
              ]);
              console.log(this.tableData, "tableData");
            } else {
              this.$message.error("取消预约失败!");
            }
          });
        })
        .catch(() => {
          this.$message.info("未执行取消预约");
        });
    },
  },
};
</script>
<style scoped></style>
